package com.tzbank.esb.consumer;

import java.util.HashMap;
import java.util.Map;

import org.springframework.cglib.beans.BeanMap;

import com.dc.eai.data.CompositeData;
import com.dcfs.esb.client.ESBClient;
import com.tzbank.esb.util.CodeUtil;
import com.tzbank.esb.util.EsbConversionUtil;
import com.tzbank.esb.util.ResultUtil;

/**
 * @author youkun
 * esb调用的公共方法
 */
public class EsbBeanConsumerUtil {

    public static Map esbConsumer(Object bean){
        // Map转换Esb报文
        CompositeData reqCompositeData = null;

        try {
            reqCompositeData = EsbConversionUtil.mapToCompositeData(BeanMap.create(bean));
        } catch (Exception e) {
            return ResultUtil.resultMap(CodeUtil.CODE_500.getName(), CodeUtil.CODE_500.getCode(), null);
        }

        CompositeData respCompositeData = null;
        // 调用核心服务
        try {
            respCompositeData = ESBClient.request(reqCompositeData);
        } catch (Exception e) {
            return ResultUtil.resultMap(CodeUtil.CODE_500.getName(), CodeUtil.CODE_500.getCode(), null);
        }
        //通过核心所返回标志Code=000000来判断调用核心计价因子是否调用成功
        String code = (String) respCompositeData.getStruct("SYS_HEAD").getArray("RET").getStruct(0)
                .getField("RET_CODE").getValue();
        //获取msg信息
        String msg = (String) respCompositeData.getStruct("SYS_HEAD").getArray("RET").getStruct(0)
                .getField("RET_MSG").getValue();
        if (code != null && !code.equals("000000")) {
            return ResultUtil.resultMap(CodeUtil.CODE_500.getName(), CodeUtil.CODE_500.getCode(), null);
        }

        // Esb报文转换Map
        Map<String, Object> outputMap = new HashMap<>();
        try {
            outputMap = EsbConversionUtil.compositeDataToMap(respCompositeData);
            System.out.println(outputMap);
        } catch (Exception e) {
            return ResultUtil.resultMap(CodeUtil.CODE_500.getName(), CodeUtil.CODE_500.getCode
                    (), null);
        }

        return ResultUtil.resultMap(CodeUtil.CODE_200.getName(), CodeUtil.CODE_200.getCode(), null);
    }
}
